package csl.blog.server.config.memcached;

import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author chensl
 * @date 2023-04-14 15:05:49
 * @description
 */
@Slf4j
@Configuration
public class MemcachedConfig {

    @Resource
    @Autowired
    private MemcachedProperties memcachedProperties;

    @Bean(name = "memcachedClientBuilder")
    public MemcachedClientBuilder getBuilder() {
        XMemcachedClientBuilder xMemcachedClientBuilder = new XMemcachedClientBuilder(memcachedProperties.getServers());
//        内部采用一致性哈希算法
        xMemcachedClientBuilder.setSessionLocator(new KetamaMemcachedSessionLocator());
        xMemcachedClientBuilder.setOpTimeout(memcachedProperties.getOpTimeout());
//        采用二进制传输协议（默认为文本协议）
        xMemcachedClientBuilder.setCommandFactory(new BinaryCommandFactory());
        xMemcachedClientBuilder.setConnectionPoolSize(memcachedProperties.getPoolSize());
//        是否开启失败模式
        xMemcachedClientBuilder.setFailureMode(memcachedProperties.getFailureMode());
        return xMemcachedClientBuilder;
    }

    @Bean(name = "memcachedClient")
    public MemcachedClient getClient(@Qualifier("memcachedClientBuilder") MemcachedClientBuilder memcachedClientBuilder) {
        MemcachedClient client = null;
        try {
            client = memcachedClientBuilder.build();
        } catch (Exception e) {
            log.error("Exception happens when build memcached client: {}",e.getMessage());
        }
        return client;
    }
}
